package com.jyy.utils.dynamicdatasource.config;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;

import java.sql.SQLException;

/**
 * 配置多数据源
 *
 * @author jyy
 * @data 2025-01-14
 */
@Slf4j
@Configuration
public class DynamicDataSourceConfig {

    /**
     * 从配置文件中获取配置
     *
     * @return 数据源配置对象
     */
    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.druid")
    public DataSourceProperties dataSourceProperties() {
        return new DataSourceProperties();
    }

    /**
     * 默认数据源
     *
     * @param properties 数据源配置对象
     * @return 数据源对象
     */
    @Bean
    public DruidDataSource defaultDataSource(DataSourceProperties properties) {
        // 默认数据源,通过配置获取创建
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(properties.getDriverClassName());
        druidDataSource.setUrl(properties.getUrl());
        druidDataSource.setUsername(properties.getUsername());
        druidDataSource.setPassword(properties.getPassword());
        try {
            druidDataSource.init();
        } catch (SQLException e) {
            log.error(e.toString());
        }
        return druidDataSource;
    }

    /**
     * 初始化数据源
     *
     * @param defaultDataSource 默认数据源
     * @return 动态数据源
     */
    @Bean
    @Primary
    @DependsOn({"defaultDataSource"})
    public DynamicDataSource dynamicDataSource(DruidDataSource defaultDataSource) {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        // 设置targetDataSources(通过数据库配置获取，首次创建没有数据源)
        dynamicDataSource.setTargetDataSources(DynamicDataSource.targetDataSources);

        // 默认数据源
        dynamicDataSource.setDefaultTargetDataSource(defaultDataSource);

        log.info("------- 初始化数据源 -------");
        return dynamicDataSource;
    }

}
